import { Component, Directive } from "@vue/runtime-core";
import $store from "../store";
import { $pushRoute, useGlobalMessage } from "../utils/global";

export default {
  name: 'permission',
  mounted(el, binding) {
    const {
      arg: evtName,
      value,
      instance = {} as any,
    } = binding;
    if (!evtName) return;
    const evts: any = instance.__permissionEvts || (instance.__permissionEvts = {});
    const handler = evts[evtName] || (evts[evtName] = function (...args: any[]) {
      if (!$store.getters.getUserInfo) {
        useGlobalMessage().warning('请先登录');
        return;
      }
      value.apply(null, args);
    })
    el.addEventListener(evtName, handler);
  },
  unmounted(el, binding) {
    const {
      arg: evtName,
      instance = {} as any,
    } = binding;
    if (!evtName) return;
    const evts: any = instance.__permissionEvts || (instance.__permissionEvts = {});
    const handler = evts[evtName];
    el.removeEventListener(evtName, handler);
  }
} as Directive;